package com.ruoyi.goods.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

public class OSSUtil {
    // 从配置文件中读取OSS相关配置

    static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    static String furl = "https://alibiabia.oss-cn-beijing.aliyuncs.com/";

    static String accessKeyId = "LTAI5t9fBwG6HdT1VDdzX9cp";
    static String accessKeySecret = "XWb86dc7YSPzDN2Kcf49n44lwIGzvC";
    // 填写Bucket名称。
    static String bucketName = "alibiabia";

    private static String objectName = "file/";


    /**
     * 上传文件到OSS
     *
     * @param fileName    文件名
     * @param inputStream 文件输入流
     * @return 文件的访问URL
     */
    public static String upload(String fileName, InputStream inputStream) {
        // 组合objectName
        String fullObjectName = objectName + fileName;

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件
            PutObjectResult result = ossClient.putObject(bucketName, fullObjectName, inputStream);
            // 返回文件的访问URL
            return furl + "/" + fullObjectName;
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}
